import React, { Component, Fragment } from "react";
import "./Tabbar.scss";

export default class Tabbar extends Component {
  state = {
    activeTab: "home",
    //   定义组件和路由的关系
    activeTabPathMap: {
      home: "/home",
      category: "/category",
      buy: "/buy",
      cart: "/car",
      personal: "/personal",
    }
  };

  handleHashChange = (params) => {
    let activeTab = this.props.match.url.split('/')[1];
    this.setState({
      activeTab: activeTab
    })
  }

  //挂载时
  componentDidMount() {
    // console.log(this.props);
    let activeTab = this.props.match.url.split('/')[1];
    this.setState({
      activeTab: activeTab
    });
    //监听hash的变化
    window.addEventListener('hashchange', this.handleHashChange);
  }
  handleClick = (params) => {
    //   console.log(params);
    this.setState({
      activeTab: params
    });
    // console.log(this.props);
    this.props.history.push(this.state.activeTabPathMap[params]);
  };

  //卸载时 移除hashchange监听事件
  componentWillUnmount() {
    window.removeEventListener('hashchange', this.handleHashChange);
  }


  render() {
    return (
      <Fragment>
        <div className="tabbarWrap">
          <div className="tabbarContent">{/* 内容布冯 */}{this.props.children}</div>
          {/* 底部按钮 */}
          <div className="footerWrap">
            <div className="footItem" onClick={this.handleClick.bind(this, 'home')}>
              <i className={this.state.activeTab === "home" ? "icon icon-home-o" : "icon icon-home"}></i>
              <span className={this.state.activeTab === "home" ? "active" : ""}>首页</span>
            </div>
            <div className="footItem" onClick={this.handleClick.bind(this, 'category')}>
              <i className={this.state.activeTab === "category" ? "icon icon-community-o" : "icon icon-community"}></i>
              <span className={this.state.activeTab === "category" ? "active" : ""}>分类</span>
            </div>
            <div className="footItem" onClick={this.handleClick.bind(this, 'buy')}>
              <i className={this.state.activeTab === "buy" ? "icon icon-valbug-o" : "icon icon-valbug"}></i>
              <span className={this.state.activeTab === "buy" ? "active" : ""}>值得买</span>
            </div>
            <div className="footItem" onClick={this.handleClick.bind(this, 'cart')}>
              <i className={this.state.activeTab === "car" ? "icon icon-cart-o" : "icon icon-cart"}></i>
              <span className={this.state.activeTab === "car" ? "active" : ""}>购物车</span>
            </div>
            <div className="footItem" onClick={this.handleClick.bind(this, 'personal')}>
              <i className={this.state.activeTab === "personal" ? "icon icon-my-o" : "icon icon-my"}></i>
              <span className={this.state.activeTab === "personal" ? "active" : ""}>个人</span>
            </div>
          </div>
        </div>
      </Fragment>
    );
  }
}
